import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Drawer, Message, Checkbox } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useRef, useState, useEffect } from 'react';
import DataForm from './components/DataForm';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import { toJS } from 'mobx';
import QR from './components/QR';
import moment from 'moment';
import ComponentsDrawer from '@/components/Drawers/ComponentsDrawer';
import PartnerGroup from './components/PartnerGroup';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';

const tableId = uniqueId('tauTable-');

const Partner = () => {
  const [modal, setModal] = useState([]);
  const { partnerStore: store } = useStore();
  const [QRModal, setQRModal] = useState({});
  const [showPartner, setShowPartner] = useState(false);
  const [data, setData] = useState([]);
  const [showCustomerMark, setShowCustomerMark] = useState(false);
  const [showRemuneration, setShowRemuneration] = useState(false);
  const [counts, setCounts] = useState([]);
  const [remuneration, setRemuneration] = useState([]);
  const partnerRef = useRef();

  // 监听合伙人
  useEffect(() => {
    if (showPartner) {
      (async () => {
        const res = await fetchCcOrderCounts();
        setData(res);
      })();
    } else {
      setData([]);
    }
  }, [showPartner, store.partner]);

  useEffect(() => {
    if (showCustomerMark) {
      (async () => {
        const res = await fetchCustomerMarkCounts();
        setCounts(res);
      })();
    } else {
      setCounts([]);
    }
  }, [showCustomerMark, store.partner]);

  useEffect(() => {
    if (showRemuneration) {
      (async () => {
        const res = await fetchRemunerationCounts();
        setRemuneration(res);
      })();
    } else {
      setCounts([]);
    }
  }, [showRemuneration, store.partner]);

  async function fetchCcOrderCounts() {
    const promiseAry = store.partner.map((p) => store.api.getGroupCount({
      search: {
        username: p.id,
      },
    }).then((r) => ({ id: p.id, count: r })));
    return Promise.all(promiseAry);
  }

  // 获取拉新数量
  async function fetchCustomerMarkCounts() {
    const promiseAry = store.partner.map(async (p) => {
      const merchant = await store.api.getCustomerUser(p?.id);
      return store.getCustomers({
        search: {
          inviteCodes: [`${merchant?.inviteCode}-2`],
        },
      }).then((r) => ({
        id: p.id, count: r, inviteCodes: [`${merchant?.inviteCode}-2`],
      }));
    });
    return Promise.all(promiseAry);
  }

  // 获取佣金报酬
  async function fetchRemunerationCounts() {
    const promiseAry = store.partner.map(async (p) => {
      const merchant = await store.api.getPayTransTotal({
        targetType: 'PARTNER',
        state: '',
        targetId: p.username,
      });
      return ({
        id: p.id, total: merchant || 0,
      });
    });
    return Promise.all(promiseAry);
  }

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { registerAddr, status, getOnDate, ...searchArgs } = params.values;
    const [from, to] = getOnDate || [];
    store.search = {
      registerAddr,
      status,
      from,
      to,
      ...searchArgs,
    };
  };

  // 点击打开添加
  // eslint-disable-next-line no-unused-vars
  const handleOpenAdd = () => {
    partnerRef.current = {};
    setModal(['add']);
  };

  // 点击打开编辑
  const handleOpenEdit = (company) => {
    partnerRef.current = company;
    setModal(['edit']);
  };

  // 是否禁用
  const changeUpdate = (partner) => {
    store.updateStatus(partner);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 打开二维码
  const handelOpenQR = async (partner) => {
    /**
     * data: Object, //对象数据
     * open: boolean, // 打开关闭modal
     * onCancel: () => void, // 关闭modal事件
     * args: any; // 解构的事件对象参数
     * describe: string, // 底部文字描述
     * modalStyle: Object; // modal样式
     * baseUrl: string, // url核心链接 必填
     * okText: string, // 自定义确定按钮文字
     * cancelText: string, // 自定义取消按钮文字
     */
    try {
      const { username, fullname } = partner;
      setQRModal({
        ...QRModal,
        open: true,
        okText: '下载',
        // baseUrl,
        // twoUrl,
        username,
        onCancel: CROnCancel,
        name: fullname,
      });
    } catch (error) {
      console.log('🚀 _ file: index.jsx:139 _ error:', error);
    }
  };

  const CROnCancel = () => {
    setQRModal({ open: false });
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        if (result.partnerInfo.discountInfo?.failureTime) {
          // eslint-disable-next-line no-param-reassign
          result.partnerInfo.discountInfo.failureTime = moment.utc(result.partnerInfo.discountInfo?.failureTime).toISOString();
        }
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 新增订单数据提交
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        if (result.partnerInfo.discountInfo?.failureTime) {
          // eslint-disable-next-line no-param-reassign
          result.partnerInfo.discountInfo.failureTime = moment.utc(result.partnerInfo.discountInfo?.failureTime).toISOString();
        }
        await store.create(toJS(result));
        Message.success({ content: t`合伙人创建成功` });
      } catch (e) {
        Message.error({ content: t`合伙人创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 查看包车订单
  const handleOpenCCOrder = (result) => {
    partnerRef.current = result;
    setModal(['ccOrder']);
  };

  // 查看专线订单
  const handleOpenSCOrder = (result) => {
    partnerRef.current = result;
    setModal(['scOrder']);
  };

  // 查看巴士订单
  const handleOpenBusOrder = (result) => {
    partnerRef.current = result;
    setModal(['busOrder']);
  };

  // 查看合伙人团队
  const handelViewGroup = (result) => {
    partnerRef.current = result;
    setModal(['group']);
  };

  // 查看客户信息
  const handleOpenCustomer = async (result) => {
    partnerRef.current = result;
    setModal(['customer']);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          // {
          //   name: 'btn-addPartner',
          //   title: t`添加合伙人`,
          //   type: 'primary',
          //   onClick: handleOpenAdd,
          // },
        ]}
        searchItems={[
          {
            name: 'getOnDate',
            type: 'date-range',
            props: {
              placeholder: [t`注册开始时间`, t`注册结束时间`],
            },
          },
          {
            name: 'status',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.status),
              placeholder: t`全部状态`,
            },
          },
          {
            name: 'partnerType',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.partnerType),
              placeholder: t`合伙人类型`,
            },
          },
        ]}
        extraItems={[
          {
            name: 'cbx-showDriver',
            component: <Checkbox style={{ marginLeft: 10 }} onChange={(v) => setShowPartner(v)}>{t`查看合伙人团队`}</Checkbox>,
          },
          {
            name: 'cbx-customerMarkCount',
            component: <Checkbox style={{ marginLeft: 10 }} onChange={(v) => setShowCustomerMark(v)}>{t`查看客户绑定`}</Checkbox>,
          },
          {
            name: 'cbx-commissionTotal',
            component: <Checkbox style={{ marginLeft: 10 }} onChange={(v) => setShowRemuneration(v)}>{t`查看佣金总金额`}</Checkbox>,
          },
        ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.partner)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('fullname', { width: 58 }),
            column('partnerInfo.type', { width: 58 }),
            column('busOrder', {
              width: 88,
              cell: (v, _, parent) => (
                <>
                  <Button type="primary" text onClick={() => handleOpenBusOrder(parent)}>{v}</Button> / <span>{t`${(parent?.busPriceSum).toFixed(2)}`}</span>
                </>
              ),
            }),
            column('specialCarOrder', {
              width: 88,
              cell: (v, _, parent) => (
                <>
                  <Button type="primary" text onClick={() => handleOpenCCOrder(parent)}>{v}</Button> / <span>{t`${(parent?.specialCarPriceSum).toFixed(2)}`}</span>
                </>
              ),
            }),
            column('shuttleBusOrder', {
              width: 88,
              cell: (v, _, parent) => (
                <>
                  <Button type="primary" text onClick={() => handleOpenSCOrder(parent)}>{v}</Button> / <span>{t`${(parent?.shuttleBuspriceSum).toFixed(2)}`}</span>
                </>
              ),
            }),
            column('customerMarkCount', {
              width: 88,
              cell: (v, _, parent) => (
                <>
                  <Button type="primary" text onClick={() => handleOpenCustomer(parent)}>{counts.find((n) => n.id === parent.id)?.count || 0}</Button>
                </>
              ),
            }),
            column('orderAmount', {
              width: 88,
              cell: (_, __, parent) => {
                const { busPriceSum, specialCarPriceSum, shuttleBuspriceSum } = parent;
                const totalPrice = busPriceSum + specialCarPriceSum + shuttleBuspriceSum;
                return <span>{t`${totalPrice.toFixed(2)}`}</span>;
              },
            }),
            column('totalAmount', { width: 88, cell: (__, ___, parent) => <span>{remuneration.find((n) => n.id === parent.id)?.total || 0}</span> }),
            column('partnerGroup', { width: 88, cell: (v, _, r) => <Button text type="primary" onClick={() => handelViewGroup(r)}>{data.find((p) => p.id === r.id)?.count || 0}</Button> }),
            column('partnerInfo.partnerStatus', { width: 68 }),
            column('partnerInfo.registerTime', { width: 68 }),
            {
              title: t`操作`,
              dataIndex: 'channelNumber',
              width: 180,
              cell: (_, __, partner) => {
                const funcMenu = [
                  {
                    title: t`编辑`,
                    onClick: () => handleOpenEdit(partner),
                  },
                  {
                    title: t`二维码`,
                    onClick: () => handelOpenQR(partner),
                  },
                  {
                    title: t`${ENUMS.statusText[partner.partnerInfo.partnerStatus] || '启用'}`,
                    onClick: () => changeUpdate(partner),
                  },
                ];
                return <MoreFuncDropDown dropdownItems={funcMenu} maxShow={1} />;
              },
            },
          ].filter((c) => c.dataIndex !== 'partnerGroup' || showPartner)
            .filter((c) => c.dataIndex !== 'customerMarkCount' || showCustomerMark)
            .filter((c) => c.dataIndex !== 'totalAmount' || showRemuneration)
          }
        />
      </div>
      <Drawer
        visible={modal[0] === 'add' || modal[0] === 'edit'}
        title={modal[0] === 'add' ? t`添加合伙人` : t`修改合伙人【${partnerRef.current?.fullname}】`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="90%"
      >
        <DataForm
          username={partnerRef.current?.username}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'group'}
        title={`查看【${partnerRef.current?.fullname}】合伙人团队`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="60%"
      >
        <PartnerGroup
          partnerRef={partnerRef.current}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>
      <QR modal={QRModal} />
      <ComponentsDrawer modal={modal} queryParams={{ partnerId: partnerRef.current?.username }} inviteCodes={counts.find((p) => p.id == partnerRef.current?.id)?.inviteCodes || []} name={partnerRef.current?.fullname} onCancel={handleCancel} />
    </TauPage>
  );
};

export default observer(Partner);
